#include "driver_uart.h"


void uart_init(void)
{
    // USART2 时钟使能
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
    // GPIOA时钟使能
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    
    //初始化TX引脚 PA2
    GPIO_InitTypeDef stGPIOInitDef;
    GPIO_StructInit(&stGPIOInitDef);
    stGPIOInitDef.GPIO_Mode = GPIO_Mode_AF_PP; 
    stGPIOInitDef.GPIO_Speed = GPIO_Speed_50MHz;
    stGPIOInitDef.GPIO_Pin = UART_TX;
    GPIO_Init(GPIO_PORT, &stGPIOInitDef);

    //初始化RX引脚 PA3
    stGPIOInitDef.GPIO_Mode = GPIO_Mode_IPU; 
    stGPIOInitDef.GPIO_Speed = GPIO_Speed_50MHz;
    stGPIOInitDef.GPIO_Pin = UART_RX;
    GPIO_Init(GPIO_PORT, &stGPIOInitDef);

    //配置USART2
    USART_InitTypeDef stUSARTInitDef;
    USART_StructInit(&stUSARTInitDef);
    stUSARTInitDef.USART_BaudRate = 115200;			//波特率
    stUSARTInitDef.USART_HardwareFlowControl = USART_HardwareFlowControl_None;			//无硬件流控
    stUSARTInitDef.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;							//开启发送、接收
    stUSARTInitDef.USART_Parity = USART_Parity_No;										//无校验
    stUSARTInitDef.USART_StopBits = USART_StopBits_1;									//一位停止位
    stUSARTInitDef.USART_WordLength = USART_WordLength_8b;								//八位数据位
    USART_Init(USART2, &stUSARTInitDef);
	
	// 配置USART2 NVIC
	NVIC_InitTypeDef stNVICInitDef;
	stNVICInitDef.NVIC_IRQChannel = USART2_IRQn;
    stNVICInitDef.NVIC_IRQChannelCmd = ENABLE;
    stNVICInitDef.NVIC_IRQChannelPreemptionPriority = 4;
    stNVICInitDef.NVIC_IRQChannelSubPriority = 0;
	NVIC_Init(&stNVICInitDef);
	
	//开启中断
	USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
	USART_ClearFlag(USART2, USART_IT_RXNE);
	USART_ITConfig(USART2, USART_IT_IDLE, ENABLE);
	USART_ClearFlag(USART2, USART_IT_IDLE);

    //开启串口
    USART_Cmd(USART2, ENABLE);
}

void uart_send_byte(uint8_t byte)
{
	//等待串口发送寄存器为空
    while(USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
	USART_SendData(USART2, byte);
}

uint8_t uart_read_byte(void)
{
    while(!USART_GetFlagStatus(USART2, USART_FLAG_RXNE));
    return USART_ReceiveData(USART2);
}

#ifdef __cplusplus
extern "C"
{
#endif


#ifdef __cplusplus
}
#endif



